package com.medical.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.system.converter.RoleConverter;
import com.medical.system.mapper.SysRoleMapper;
import com.medical.system.model.entity.SysRole;
import com.medical.system.model.entity.SysRoleMenu;
import com.medical.system.model.form.RoleForm;
import com.medical.system.model.query.RolePageQuery;
import com.medical.system.service.SysRoleMenuService;
import com.medical.system.service.SysRoleService;
import com.medical.system.service.SysUserRoleService;
import com.medical.system.model.vo.RolePageVO;
import com.medical.web.model.Option;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final RoleConverter roleConverter;
    private final SysUserRoleService userRoleService;
    private final SysRoleMenuService roleMenuService;

    @Override
    public Page<RolePageVO> getRolePage(RolePageQuery pageQuery) {
        int pageNum = pageQuery.getPageNum();
        int pageSize = pageQuery.getPageSize();
        String keywords = pageQuery.getKeywords();
        Page<SysRole> rolePage = this.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<SysRole>()
                .and(StrUtil.isNotBlank(keywords),
                        wrapper -> wrapper.like(StrUtil.isNotBlank(keywords), SysRole::getName, keywords)
                        .or()
                        .like(StrUtil.isNotBlank(keywords), SysRole::getCode, keywords)));
                //非管理员人员看不到管理员角色
//                .ne(!SecurityUtils.isRoot(),SysRole::getCode, SystemConstants.ROOT_ROLE_CODE));
        return roleConverter.entity2Page(rolePage);
    }

    @Override
    public List<Option> listRoleOptions() {
        List<SysRole> roleList =  list(new LambdaQueryWrapper<SysRole>()
//                .ne(!SecurityUtils.isRoot(), SysRole::getCode, SystemConstants.ROOT_ROLE_CODE)
                .select(SysRole::getId, SysRole::getName)
                .orderByAsc(SysRole::getSort));
        return roleConverter.entities2Options(roleList);
    }

    @Override
    public boolean saveRole(RoleForm roleForm) {
        Long roleId = roleForm.getId();
        //编辑角色时，判断角色是否存在
        SysRole oldRole = null;
        if (roleId != null) {
            oldRole = getById(roleId);
            Assert.isTrue(oldRole != null, "角色不存在");
        }
        String roleCode = roleForm.getCode();
        long count = this.count(new LambdaQueryWrapper<SysRole>()
                .ne(roleId != null, SysRole::getId, roleId)
                .and(wrapper -> wrapper
                        .eq(SysRole::getCode, roleCode)
                        .or()
                        .eq(SysRole::getName, roleForm.getName())));
        Assert.isTrue(count == 0, "角色名称或角色编码已存在，请修改重试");
        //实体交换
        SysRole sysRole = roleConverter.form2Entity(roleForm);
        boolean result = saveOrUpdate(sysRole);
        if (result) {
            //判断角色编码或角色状态是否修改，修改了则刷新缓存
            if (oldRole != null
                    && !StrUtil.equals(oldRole.getCode(), roleCode)
                    && !ObjectUtil.equals(oldRole.getStatus(), roleForm.getStatus())) {
                roleMenuService.refreshRolePermsCache(roleCode);
            }
        }
        return result;
    }

    @Override
    public RoleForm getRoleForm(Long roleId) {
        SysRole sysRole = getById(roleId);
        return roleConverter.entity2Form(sysRole);
    }

    @Override
    @Transactional
    public boolean updateRoleStatus(Long roleId, Integer status) {
        SysRole sysRole = getById(roleId);
        Assert.isTrue(sysRole != null, "角色不存在");
        sysRole.setStatus(status);
        boolean result = updateById(sysRole);
        if (result) {
            //刷新角色权限缓存
            roleMenuService.refreshRolePermsCache(sysRole.getCode());
        }
        return result;
    }

    @Override
    public boolean deleteRoles(String ids) {
        List<Long> roleIds = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        for (Long roleId : roleIds) {
            SysRole role = this.getById(roleId);
            Assert.isTrue(role != null, "角色不存在");
            //判断角色是否被用户关联
            boolean isRoleAssigned = userRoleService.hasAssignedUsers(roleId);
            Assert.isTrue(!isRoleAssigned, "角色【{}】已分配用户，请先解除关联后删除", role.getName());
            boolean deleteResult = removeById(role);
            if (deleteResult) {
                // 删除成功，刷新角色对应的权限缓存
                roleMenuService.refreshRolePermsCache(role.getCode());
            }
        }
        return true;
    }

    @Override
    public List<Long> getRoleMenuIds(Long roleId) {
        return roleMenuService.listMenuIdsByRoleId(roleId);
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = "menu", key = "'routes'")
    public boolean assignMenusToRole(Long roleId, List<Long> menuIds) {
        SysRole sysRole = getById(roleId);
        Assert.isTrue(sysRole != null, "角色不存在");
        // 先删除角色菜单
        roleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
        //新增角色菜单
        if (CollectionUtil.isNotEmpty(menuIds)) {
            List<SysRoleMenu> roleMenus = menuIds.stream()
                    .map(menuId -> new SysRoleMenu(roleId, menuId))
                    .collect(Collectors.toList());
            roleMenuService.saveBatch(roleMenus);
        }
        roleMenuService.refreshRolePermsCache(sysRole.getCode());
        return true;
    }

    @Override
    public Integer getMaxDataRangeDataScope(Set<String> roles) {
        return this.baseMapper.getMaxDataRangeDataScope(roles);
    }
}
